// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/exec/task_trace_writer.h>
#include <pollux/common/file/file.h>
#include <pollux/core/plan_node.h>
#include <pollux/core/query_ctx.h>
#include <pollux/exec/trace.h>
#include <pollux/exec/trace_util.h>

namespace kumo::pollux::exec::trace {
    TaskTraceMetadataWriter::TaskTraceMetadataWriter(
        std::string traceDir,
        memory::MemoryPool * /* pool */)
        : traceDir_(std::move(traceDir)),
          fs_(filesystems::getFileSystem(traceDir_, nullptr)),
          traceFilePath_(getTaskTraceMetaFilePath(traceDir_)) {
        POLLUX_CHECK_NOT_NULL(fs_);
        POLLUX_CHECK(!fs_->exists(traceFilePath_));
    }

    void TaskTraceMetadataWriter::write(
        const std::shared_ptr<core::QueryCtx> &queryCtx,
        const core::PlanNodePtr &planNode) {
        POLLUX_CHECK(!finished_, "Query metadata can only be written once");
        finished_ = true;
        melon::Dynamic queryConfigObj = melon::Dynamic::object;
        const auto configValues = queryCtx->queryConfig().rawConfigsCopy();
        for (const auto &[key, value]: configValues) {
            queryConfigObj[key] = value;
        }

        melon::Dynamic connectorPropertiesObj = melon::Dynamic::object;
        for (const auto &[connectorId, configs]:
             queryCtx->connectorSessionProperties()) {
            melon::Dynamic obj = melon::Dynamic::object;
            for (const auto &[key, value]: configs->rawConfigsCopy()) {
                obj[key] = value;
            }
            connectorPropertiesObj[connectorId] = obj;
        }

        melon::Dynamic metaObj = melon::Dynamic::object;
        metaObj[TraceTraits::kQueryConfigKey] = queryConfigObj;
        metaObj[TraceTraits::kConnectorPropertiesKey] = connectorPropertiesObj;
        metaObj[TraceTraits::kPlanNodeKey] = planNode->serialize();

        const auto metaStr = melon::toJson(metaObj);
        const auto file = fs_->openFileForWrite(traceFilePath_);
        file->append(metaStr);
        file->close();
    }
} // namespace kumo::pollux::exec::trace
